package com.twu.biblioteca.library;

import com.twu.biblioteca.book.BookFactory;
import com.twu.biblioteca.customer.Customer;
import com.twu.biblioteca.movie.Movie;

import java.util.*;

public class Library {
	private Map<Integer, Integer> books = new HashMap<Integer, Integer>();
	private List<Movie> movies = new LinkedList<Movie>();
	private List<Customer> customers = new LinkedList<Customer>();

	public Library() {
		bookInitialize();
		moiveInitialize();
		customerInitialize();
	}

	private void bookInitialize() {
		addBook(BookNumber.EXTREME_PROGRAMMING_EXPLAINED, 1);
		addBook(BookNumber.REFACTORING, 1);
		addBook(BookNumber.TEST_DRIVEN_DEVELOPMENT, 1);
	}

	private void moiveInitialize() {
		movies.add(new Movie("Sholay", 1975, "Ramesh Sippy", "N/A"));
		movies.add(new Movie("JustMakeUpOne", 2013, "Benwei", "N/A"));
	}

	private void customerInitialize() {
		customers.add(new Customer("111-1111", "12345", "name@thoughtworks.com", "282882993"));
		customers.add(new Customer("111-1112","12345","name2@thoughtworks.com","282882994"));
	}

	public String listAllBooks() {
		BookFactory bookFactory = new BookFactory();
		StringBuilder sb = new StringBuilder();
		for (int i = 1; i <= books.size(); i++) {
			sb.append(i).append(".").append(bookFactory.createBook(i).getName()).append("\n");
		}
		return sb.toString();
	}

	public boolean lendBook(int bookNum, Customer customer) {
		if (books.containsKey(bookNum)) {
			int num = books.get(bookNum);
			if (num > 0) {
				reduceBookCount(bookNum, num);
				customer.borrow(bookNum);
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}

	private void reduceBookCount(int bookNum, int num) {
		books.remove(bookNum);
		books.put(bookNum, num - 1);
	}

	public void addBook(int bookNum, int count) {
		if (books.containsKey(bookNum)) {
			int currentCount = books.get(bookNum);
			books.remove(bookNum);
			books.put(bookNum, currentCount + currentCount);
		} else {
			books.put(bookNum, count);
		}
	}

	public int getBookCount(int bookNum) {
		return books.get(bookNum);
	}

	public String listAllMovies() {
		StringBuilder sb = new StringBuilder();
		sb.append("Movie\tYear\tDirector\tRating\n");
		for (Movie movie : movies) {
			sb.append(movie.getDetails()).append("\n");
		}
		return sb.toString();
	}

	public List<Customer> getCustomers() {
		return customers;
	}
}
